import { useState, useEffect, useContext } from 'react';
import { NavBar, List, Switch, Button } from 'antd-mobile';
import { useHistory } from 'react-router-dom';

import { globalJump } from '../../../utils';
import { MySdkStoreContext } from '../../../context';

const flatObject = (obj) => {
  let newObj = {};

  Object.keys(obj).forEach(key => {
    if (typeof obj[key] === 'object') {
      newObj = { ...newObj, ...obj[key]};
    } else {
      newObj[key] = obj[key];
    }
  });

  return newObj;
}

export default function() {
  const history = useHistory();
  const mySdkStore = useContext(MySdkStoreContext);
  const [mySetting, setMySetting] = useState({});

  useEffect(async () => {
    const setting = await mySdkStore.sdk.querySecretConfig();
    setMySetting(flatObject(setting));
  }, []);

  const handleChangeSetting = async ({ property, value }) => {
    await mySdkStore.sdk.changeSecretConfig({ property, value });
    setMySetting({ ...mySetting, [property]: value });
  }

  const handleLoginOut = () => {
    // var cookies = document.cookie.split(";");
    // for (const cookie of cookies) {
    //   const eqPos = cookie.indexOf("=");
    //   const name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
    //   console.log(name, eqPos)
    //   document.cookie = name +"=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
    //   console.log(document.cookie)
    // }
    mySdkStore.sdk.close();
    document.cookie = `im_userId=;expires=Thu, 01 Jan 1970 00:00:00 GMT`;
    globalJump("#/loginByUserId");
  }

  return (<div className="mySettingPage">
    <NavBar onBack={() => history.goBack()} style={{ background: '#fff', border: 'none' }}>设置</NavBar>
    <List style={{ '--border-top': 0, '--border-bottom': 0, '--border-inner': 0, marginTop: 12 }}>
      <List.Item extra={<Switch onChange={(value) => handleChangeSetting({ property: 'enableVerificationWhenAddMe', value: !value} )} checked={!mySetting.enableVerificationWhenAddMe} />}>
        加我好友时无须验证
      </List.Item>
    </List>
    {/* todo: 密聊设置什么 */}
    {/* <List style={{ '--border-top': 0, '--border-bottom': 0, '--border-inner': 0, marginTop: 12 }}>
      <List.Item onClick={() => {}}>
        密聊设置
      </List.Item>
    </List> */}
    <List style={{ '--border-top': 0, '--border-bottom': 0, '--border-inner': 0, marginTop: 12 }}>
      <List.Item onClick={() => history.push({ pathname: '/globalSetting' })}>
        通用设置
      </List.Item>
    </List>
    <div style={{ margin: '20px 12px' }}>
      <Button block color="danger" fill='outline' onClick={handleLoginOut}>退出登录</Button>
    </div>
  </div>)
}